package com.hyperfix.washer.common;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author JiangChunYu
 * 2024/4/30
 */
@Component
public class StatusRegistrar implements DisposableBean {
    private final Map<Integer, Session> sessions = new ConcurrentHashMap<>(16);

    public void addSession(Integer userId, Session session) {
        this.sessions.put(userId, session);
    }


    public void removeSession(Integer userId) {
        Session session = this.sessions.remove(userId);
        if (session != null) {
            try {
                session.close();
            } catch (IOException e) {
                throw new RuntimeException("close session error", e);
            }
        }
    }


    public Collection<Session> getAllSession() {
        return sessions.values();
    }

    @Override
    public void destroy() {
        this.sessions.clear();
    }
}
